<template>
  <div class="popup-rule-form">
    <el-form 
      ref="formRef" 
      :model="form" 
      :rules="rules" 
      label-width="120px"
      @submit.prevent="handleSubmit"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="规则名称" prop="name" required>
            <el-input 
              v-model="form.name" 
              placeholder="请输入规则名称"
              maxlength="50"
              show-word-limit
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="规则描述" prop="description" required>
            <el-input 
              v-model="form.description" 
              placeholder="请输入规则描述"
              maxlength="100"
              show-word-limit
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="触发类型" prop="triggerType" required>
            <el-select 
              v-model="form.triggerType" 
              placeholder="请选择触发类型" 
              style="width: 100%"
              @change="handleTriggerTypeChange"
            >
              <el-option label="立即触发" value="immediate" />
              <el-option label="延迟触发" value="delay" />
              <el-option label="退出意图" value="exit_intent" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status" required>
            <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
              <el-option label="启用" value="active" />
              <el-option label="禁用" value="inactive" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 延迟触发设置 -->
      <el-form-item 
        v-if="form.triggerType === 'delay'" 
        label="延迟时间" 
        prop="delaySeconds"
        required
      >
        <el-input-number 
          v-model="form.delaySeconds" 
          :min="1" 
          :max="60" 
          placeholder="延迟秒数"
          style="width: 200px;"
        />
        <span class="form-tip">秒后触发弹窗</span>
      </el-form-item>

      <!-- 弹窗内容配置 -->
      <!-- <el-divider content-position="left">弹窗内容配置</el-divider>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="弹窗标题" prop="popupTitle" required>
            <el-input 
              v-model="form.popupTitle" 
              placeholder="请输入弹窗标题"
              maxlength="50"
              show-word-limit
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="弹窗样式" prop="popupStyle">
            <el-select v-model="form.popupStyle" placeholder="请选择弹窗样式" style="width: 100%">
              <el-option label="默认样式" value="default" />
              <el-option label="优惠券样式" value="coupon" />
              <el-option label="活动样式" value="activity" />
              <el-option label="简约样式" value="simple" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="弹窗内容" prop="popupContent" required>
        <el-input 
          v-model="form.popupContent" 
          type="textarea" 
          :rows="4"
          placeholder="请输入弹窗内容描述"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="按钮文字" prop="buttonText" required>
        <el-input 
          v-model="form.buttonText" 
          placeholder="例如：立即领取、查看详情"
          maxlength="20"
          show-word-limit
        />
      </el-form-item> -->

      <!-- 展示条件设置 -->
      <el-divider content-position="left">展示条件</el-divider>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="用户类型" prop="showConditions.userType" required>
            <el-select 
              v-model="form.showConditions.userType" 
              placeholder="请选择用户类型" 
              style="width: 100%"
            >
              <el-option label="全部用户" value="all" />
              <el-option label="新用户" value="new" />
              <el-option label="老用户" value="returning" />
              <el-option label="VIP用户" value="vip" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备类型" prop="showConditions.deviceType" required>
            <el-select 
              v-model="form.showConditions.deviceType" 
              placeholder="请选择设备类型" 
              style="width: 100%"
            >
              <el-option label="全部设备" value="all" />
              <el-option label="桌面端" value="desktop" />
              <el-option label="移动端" value="mobile" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="生效日期" prop="showConditions.dayOfWeek" required>
        <el-checkbox-group v-model="form.showConditions.dayOfWeek">
          <el-checkbox :value="1">周一</el-checkbox>
          <el-checkbox :value="2">周二</el-checkbox>
          <el-checkbox :value="3">周三</el-checkbox>
          <el-checkbox :value="4">周四</el-checkbox>
          <el-checkbox :value="5">周五</el-checkbox>
          <el-checkbox :value="6">周六</el-checkbox>
          <el-checkbox :value="7">周日</el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item label="时间范围">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-time-picker
              v-model="timeRange.start"
              placeholder="开始时间"
              format="HH:mm"
              value-format="HH:mm"
              style="width: 100%"
            />
          </el-col>
          <el-col :span="12">
            <el-time-picker
              v-model="timeRange.end"
              placeholder="结束时间"
              format="HH:mm"
              value-format="HH:mm"
              style="width: 100%"
            />
          </el-col>
        </el-row>
      </el-form-item>

      <!-- 频率限制设置 -->
      <el-divider content-position="left">频率限制</el-divider>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="最大展示次数" prop="frequencyLimit.maxShows" required>
            <el-input-number 
              v-model="form.frequencyLimit.maxShows" 
              :min="1" 
              :max="100" 
              placeholder="最大展示次数"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="限制周期" prop="frequencyLimit.period" required>
            <el-select 
              v-model="form.frequencyLimit.period" 
              placeholder="请选择限制周期" 
              style="width: 100%"
            >
              <el-option label="会话内" value="session" />
              <el-option label="每日" value="day" />
              <el-option label="每周" value="week" />
              <el-option label="每月" value="month" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 规则预览 -->
      <el-divider content-position="left">规则预览</el-divider>
      
      <div class="rule-preview">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="规则名称">
            {{ form.name || '未设置' }}
          </el-descriptions-item>
          <el-descriptions-item label="规则描述">
            {{ form.description || '未设置' }}
          </el-descriptions-item>
          <!-- <el-descriptions-item label="弹窗标题">
            {{ form.popupTitle || '未设置' }}
          </el-descriptions-item> -->
          <el-descriptions-item label="触发方式">
            {{ getTriggerTypeText() }}
          </el-descriptions-item>
          <el-descriptions-item label="用户范围">
            {{ getUserTypeText() }}
          </el-descriptions-item>
          <el-descriptions-item label="设备范围">
            {{ getDeviceTypeText() }}
          </el-descriptions-item>
          <el-descriptions-item label="生效日期">
            {{ getDayOfWeekText() }}
          </el-descriptions-item>
          <el-descriptions-item label="频率限制">
            {{ getFrequencyLimitText() }}
          </el-descriptions-item>
          <el-descriptions-item label="规则状态">
            <el-tag :type="form.status === 'active' ? 'success' : 'info'">
              {{ form.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <el-form-item>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          保存
        </el-button>
        <el-button @click="$emit('cancel')">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import type { Site, PopupRuleForm } from '@/types/sitePopup'

// Props
interface Props {
  form: PopupRuleForm
  sites: Site[]
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  submit: [PopupRuleForm]
  cancel: []
}>()

// 响应式数据
const formRef = ref<FormInstance>()
const submitting = ref(false)

// 确保 timeRange 对象存在
const timeRange = computed(() => {
  if (!props.form.showConditions.timeRange) {
    props.form.showConditions.timeRange = { start: '', end: '' }
  }
  return props.form.showConditions.timeRange
})

// 表单验证规则
const rules: FormRules = {
  name: [
    { required: true, message: '请输入规则名称', trigger: 'blur' },
    { min: 2, max: 50, message: '规则名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入规则描述', trigger: 'blur' },
    { min: 5, max: 100, message: '规则描述长度在 5 到 100 个字符', trigger: 'blur' }
  ],
  triggerType: [
    { required: true, message: '请选择触发类型', trigger: 'change' }
  ],
  /* popupTitle: [
    { required: true, message: '请输入弹窗标题', trigger: 'blur' },
    { min: 2, max: 50, message: '弹窗标题长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  popupContent: [
    { required: true, message: '请输入弹窗内容', trigger: 'blur' },
    { min: 5, max: 200, message: '弹窗内容长度在 5 到 200 个字符', trigger: 'blur' }
  ],
  buttonText: [
    { required: true, message: '请输入按钮文字', trigger: 'blur' },
    { min: 2, max: 20, message: '按钮文字长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  popupStyle: [
    { required: true, message: '请选择弹窗样式', trigger: 'change' }
  ], */
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  'showConditions.userType': [
    { required: true, message: '请选择用户类型', trigger: 'change' }
  ],
  'showConditions.deviceType': [
    { required: true, message: '请选择设备类型', trigger: 'change' }
  ],
  'showConditions.dayOfWeek': [
    { required: true, message: '请选择生效日期', trigger: 'change' }
  ],
  'frequencyLimit.maxShows': [
    { required: true, message: '请设置最大展示次数', trigger: 'blur' }
  ],
  'frequencyLimit.period': [
    { required: true, message: '请选择限制周期', trigger: 'change' }
  ]
}

// 方法
const handleTriggerTypeChange = () => {
  // 重置相关字段
  if (props.form.triggerType !== 'delay') {
    props.form.delaySeconds = undefined
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    // 验证时间范围
    if (props.form.showConditions.timeRange?.start && props.form.showConditions.timeRange?.end) {
      if (props.form.showConditions.timeRange.start >= props.form.showConditions.timeRange.end) {
        ElMessage.error('开始时间必须早于结束时间')
        return
      }
    }
    
    emit('submit', { ...props.form })
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitting.value = false
  }
}

// 预览文本方法
const getTriggerTypeText = () => {
  const typeMap: Record<string, string> = {
    'immediate': '立即触发',
    'delay': `延迟${props.form.delaySeconds || 0}秒触发`,
    'exit_intent': '退出意图触发'
  }
  return typeMap[props.form.triggerType] || '未设置'
}

const getUserTypeText = () => {
  const typeMap: Record<string, string> = {
    'all': '全部用户',
    'new': '新用户',
    'returning': '老用户',
    'vip': 'VIP用户'
  }
  return typeMap[props.form.showConditions.userType] || '未设置'
}

const getDeviceTypeText = () => {
  const typeMap: Record<string, string> = {
    'all': '全部设备',
    'desktop': '桌面端',
    'mobile': '移动端'
  }
  return typeMap[props.form.showConditions.deviceType] || '未设置'
}

const getDayOfWeekText = () => {
  const dayMap: Record<string, string> = {
    '1': '周一',
    '2': '周二',
    '3': '周三',
    '4': '周四',
    '5': '周五',
    '6': '周六',
    '7': '周日'
  }
  
  if (!props.form.showConditions.dayOfWeek || props.form.showConditions.dayOfWeek.length === 0) {
    return '未设置'
  }
  
  if (props.form.showConditions.dayOfWeek.length === 7) {
    return '每天'
  }
  
  return props.form.showConditions.dayOfWeek
    .map(day => dayMap[day])
    .join('、')
}

const getFrequencyLimitText = () => {
  const periodMap: Record<string, string> = {
    'session': '会话内',
    'day': '每日',
    'week': '每周',
    'month': '每月'
  }
  
  const period = periodMap[props.form.frequencyLimit.period] || '未设置'
  const maxShows = props.form.frequencyLimit.maxShows || 0
  
  return `${maxShows}次/${period}`
}
</script>

<style scoped>
.popup-rule-form {
  padding: 20px 0;
}

.form-tip {
  margin-left: 12px;
  color: #909399;
  font-size: 14px;
}

.rule-preview {
  margin: 20px 0;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-descriptions) {
  margin-top: 16px;
}

:deep(.el-divider__text) {
  font-weight: 600;
  color: #303133;
}

:deep(.el-checkbox-group) {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}
</style>
